<template>
<el-dialog title="上传客资文件" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
    <el-form ref="uploadForm" :model="uploadForm" label-width="80px">
        <el-form-item label="渠道" prop="source_id" :rules="[{ required: true, message: '请选择渠道' }]">
            <source-picker-view ref="sourcePickerRef" type="source" :checkStrictly="true" v-model="uploadForm.source_id" placeholder="请选择渠道"></source-picker-view>
        </el-form-item>

        <el-form-item label="上传" prop="hash_code" :rules="[{required:true, message:'请上传文件'}]">
            <el-upload class="upload-demo" ref="uploadRef" :action="uploadAction" :headers="headers" :show-file-list="true" :multiple="false" accept="xls,xlsx" :on-success="uploadSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
            </el-upload>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
    </el-form>
</el-dialog>
</template>

<script>
import sourcePickerView from "@/components/picker/source.vue";

import {
    getToken
} from "@/utils/auth";

import {
    doUploadApi
} from "@/api/customer/upload.js";

let uploadForm = {
    source_id: "",
    file_path: "",
    file_name: "",
    hash_code: "",
};

export default {
    components: {
        sourcePickerView,
    },
    data() {
        let headers = {};
        headers["X-Token"] = getToken();

        return {
            headers: headers,
            uploadAction: process.env.VUE_APP_BASE_API + "/api/system.file/upload",
            dialogVisible: false,
            uploadForm: Object.assign({}, uploadForm),
        };
    },
    methods: {
        showDialog() {
            this.dialogVisible = true;
            this.uploadForm = Object.assign({}, uploadForm);
            this.$nextTick(function () {
                this.$refs.uploadRef.clearFiles();
            });
        },
        uploadSuccess(res, file) {
            console.log(res, file);
            this.uploadForm.file_path = res.data.file_path;
            this.uploadForm.file_name = file.name;
            this.uploadForm.hash_code = res.data.hash_code;
        },
        submit() {
            this.$refs.uploadForm.validate((valid) => {
                if (valid) {
                    doUploadApi(this.uploadForm).then((res) => {
                        this.$message({
                            message: "上传成功",
                            type: "success",
                        });
                        this.dialogVisible = false;
                        this.$emit("uploadSuccess");
                    });
                }
            });
        },
    },
};
</script>

<style></style>
